package com.airena.controller;

import com.airena.exception.BaseException;
import com.alibaba.dashscope.audio.asr.transcription.Transcription;
import com.alibaba.dashscope.audio.asr.transcription.TranscriptionParam;
import com.alibaba.dashscope.audio.asr.transcription.TranscriptionQueryParam;
import com.alibaba.dashscope.audio.asr.transcription.TranscriptionResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.GsonBuilder;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Arrays;

/**
 * 语音转文本
 */
@RestController
@Tag(name = "语音翻译接口")
@RequestMapping("/translation")
@Slf4j
public class ASRController {

    @GetMapping
    public String translation(String fileUrl) {
        log.info("语音翻译 fileUrl:{}", fileUrl);
        // 创建转写请求参数
        TranscriptionParam param =
                TranscriptionParam.builder()
                        // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                        //.apiKey("apikey")
                        .model("fun-asr") // 此处以fun-asr为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/models
                        .fileUrls(
//                                https://dashscope.oss-cn-beijing.aliyuncs.com/samples/audio/paraformer/hello_world_female2.wav
                                Arrays.asList(fileUrl))
                        .build();
        String TranslationResult = null;
        try {
            Transcription transcription = new Transcription();
            // 提交转写请求
            TranscriptionResult result = transcription.asyncCall(param);
            System.out.println("RequestId: " + result.getRequestId());
            // 阻塞等待任务完成并获取结果
            result = transcription.wait(
                    TranscriptionQueryParam.FromTranscriptionParam(param, result.getTaskId()));
            // 处理结果
            TranslationResult =
                    getTranslationUrl(new GsonBuilder().setPrettyPrinting().create().toJson(result.getOutput()));
        } catch (Exception e) {
            System.out.println("error: " + e);
        }
        return TranslationResult;
    }

//    将翻译后的文件url取出
    private String getTranslationUrl(String json){
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = null;
        try {
            root = mapper.readTree(json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
//      解析出返回结果路径,我们只需要一个一个的处理
        String url = root.path("results").get(0).path("transcription_url").asText();
        System.out.println("转写内容 JSONURL: " + url);
        return replaceUrl(url);
    }

//    将url中的转义字符替换
    private String replaceUrl(String url){
        // 替换掉转义
        url = url.replace("\\u003d", "=").replace("\\u0026", "&");

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .GET()
                .build();

        HttpResponse<String> response = null;
        try {
            response = client.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("转写内容 JSON:");
        return getTranslationResult(response.body());
    }

//    获取最后结果
    private String getTranslationResult(String json){
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = null;
        try {
            root = mapper.readTree(json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        JsonNode transcripts = root.path("transcripts");
        if (transcripts.isArray() && transcripts.size() > 0) {
            String text = transcripts.get(0).path("text").asText();
            System.out.println("转写结果: " + text);
            return text;
        } else {
            System.out.println("没有找到转写内容");
            throw new BaseException("没有找到转写内容");
        }
    }
}
